package com.keqiang.chart.impl.pie.impl.normal

import android.view.MotionEvent
import com.keqiang.chart.impl.pie.BaseTouchHandler
import com.keqiang.chart.utils.to360Range
import kotlin.math.sqrt

/**
 * 饼状图触摸事件处理
 *
 * @author Created by wanggaowan on 2022/8/4 16:02
 */
open class PieChartTouchHandler(chart: PieChart) : BaseTouchHandler<PieChart, PieEntity>(chart) {

    override fun findClickData(e: MotionEvent): PieEntity? {
        val dataList = chart.data
        if (dataList.isNullOrEmpty()) {
            return null
        }

        val angleForPoint = getAngleForPoint(e.x, e.y)
        var entity: PieEntity? = null
        for (index in dataList.indices) {
            val data = dataList[index]
            val startAngle = data.drawStartAngle.to360Range
            if (startAngle + data.drawSweepAngle > 360) {
                if (angleForPoint >= startAngle && angleForPoint < 360) {
                    entity = data
                    break
                } else if (angleForPoint >= 0 && angleForPoint <= data.drawSweepAngle - (360 - startAngle)) {
                    entity = data
                    break
                }
            } else if (angleForPoint >= startAngle && angleForPoint <= startAngle + data.drawSweepAngle) {
                entity = data
                break
            }
        }

        if (entity == null) {
            return null
        }


        val (cx, cy) = chart.getCenter()
        val tx: Double = (e.x - cx).toDouble()
        val ty: Double = (e.y - cy).toDouble()
        val length = sqrt(tx * tx + ty * ty)
        if (length < chart.innerRadius || length > chart.radius + entity.addedRadius) {
            return null
        }

        return entity
    }
}